package com.station.client;

import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.event.dom.client.*;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.*;
import com.station.client.Distribution.Distribution;
import com.station.client.dragNDrop.*;
import com.station.client.dragNDrop.CellTable;
import com.station.client.proxies.*;

import java.util.*;

/**
 * This is the entry point class of GWT.
 * The game's will be initialized and started here.
 */
public class Base implements EntryPoint, Listener {

    CellTable cellTable;
    FlowPanel modePanel;
    AbsolutePanel gamePanel;
    TabPanel infoTabPanel;
    VerticalPanel iconPanel;
    HorizontalPanel buttonsPanel;
    public static VerticalPanel propertiesPanel;
    ExtFlexTable extPumpFlexTable;

    DialogBox dialogbox;
    VerticalPanel dialogBoxContents;
    Button dialogCloseButton;
    Label errorMessage;



    int widthL = 0;
    int heightL = 0;
    Label displayMode;


    final InlineLabel h2one = new InlineLabel("Параметры конструктора");

    Label currentMoneyInOfficeLabel = new Label("0");
    Label commonProfitLabel = new Label("0");
    Label litreHasFilled = new Label("");
    Label cost = new Label("");
    Label fuelA92Capacity = new Label("2000");
    int one = 0;

    private TextBox textBoxCash;
    private TextBox textBoxFuel;
    private PetrolPumpItem petrolPumpItem;
    private CashOfficeItem cashOfficeItem;
    private GrassItem grassItem;
    private ExitItem exitItem;
    private StartItem startItem;

    //MODEL
    private PCoordinates inCoord;
    private PCoordinates outCoord;

    Wave wave;
    static List<SimpleCar> cars;
    List<PPetrolPump> pumps;
    private static PFuelTank tank92;
    private static PFuelTank tank95;
    private static PFuelTank tankDiesel;
    private static PCoordinates fuelTankPoint;

    private static PCashOffice office;

    int redefineTargetPumpCount = 0;//счетчик, при достижении определенного значения пересчитывает ближайшие колонки для машин
    int carCreateCounter = 0; // счетчик создания машин.
    public int valueDistribution = 20;
    int indexDistribution;
    public Distribution d;
    int k1 = 0;
    int k2 = 0;

    public final static int repaintValue = 5; //сдвиг машины при движении в пикселях за один цикл
    public final static double fillingSpeed = 5.0;
    public final static int priorityQuene = 100;
    public final static double fillCoefficient = 0.7;
    public final static double refuellerFillSpeed = 50;

    public double maxA92Capacity = 2000;
    public double maxA95Capacity = 2000;
    public double maxDieselCapacity = 2000;

    private boolean isApplicationRun = false;
    private boolean isInitialized = false;

    private boolean isFuelTankEmpty = false;
    private boolean isCashOfficeFull = false;
    private boolean isRefuellerCalled = false;
    private boolean isIncasatorCalled = false;
    private double commonProfit = 0.0;
    private String finishedFuelType;


    /**
     * This is the entry point method.
     */
    public void onModuleLoad() {

        tank92 = new PFuelTank("A92", maxA92Capacity, maxA92Capacity);
        tank95 = new PFuelTank("A95", maxA95Capacity, maxA95Capacity);
        tankDiesel = new PFuelTank("DIESEL", maxDieselCapacity, maxDieselCapacity);
        cars = new ArrayList<SimpleCar>();
        pumps = new ArrayList<PPetrolPump>();

        d = new Distribution(indexDistribution, k1, k2);

        tank95.addListener(this);
        tank92.addListener(this);
        tankDiesel.addListener(this);


        initTabsheets();
        propertiesPanel = new VerticalPanel();
        iconPanel = new VerticalPanel();
        iconPanel.setStyleName("iconPanel");
        gamePanel = new AbsolutePanel();
        modePanel = new FlowPanel();
        modePanel.setHeight("50");
        buttonsPanel = new HorizontalPanel();
        buttonsPanel.setStyleName("buttonsPanel");
        dialogbox = new DialogBox(false);
        dialogbox.setWidth("300");
        dialogbox.setHeight("100");
        dialogbox.setStyleName("dialogBox");
        dialogBoxContents = new VerticalPanel();
        errorMessage = new Label("");
        dialogCloseButton = new Button("Ок");
        dialogCloseButton.setWidth("50");
        dialogCloseButton.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                dialogbox.hide();
                RootPanel.get("black").setVisible(false);
            }
        });

        Button runAppButton = new Button("Запуск");
        runAppButton.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                if (!isInitialized) {
                    setMode(false);
                    modePanel.setVisible(false);
                    infoTabPanel.setVisible(true);
                    init();

                }
                isApplicationRun = true;
                Scheduler.get().scheduleFixedPeriod(new Scheduler.RepeatingCommand() {
                    @Override
                    public boolean execute() {
                        if (isApplicationRun) {
                            lifeStep();
                            if (carCreateCounter == 30) {//valueDistribution) {
//                            if (one <= 2 || isCashOfficeFull) {
                                if (createNewCar()) {
                                    carCreateCounter = 0;
                                    valueDistribution = d.getNext();
//                                    if (!isCashOfficeFull)    //todo time
//                                        one++;
                                }

                                //}
                            } else
                                carCreateCounter++;
                            if (redefineTargetPumpCount != 10)
                                redefineTargetPumpCount++;
                            else
                                redefineTargetPumpCount = 0;
                            return true;
                        }
                        return false;

                    }
                }, 100);
            }
        });
        Button waitButton = new Button("Стоп");
        waitButton.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                isApplicationRun = false;
            }
        });
        RadioButton rb1 = new RadioButton("Procedure", "Размещение");
        RadioButton rb2 = new RadioButton("Procedure", "Редактирование");
        rb1.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {

                setMode(true);
            }
        });
        rb2.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                cellTable.isDragMode = false;
                setMode(false);
            }
        });

        displayMode = new Label("Режим : ");
        modePanel.add(displayMode);
        modePanel.add(rb1);
        modePanel.add(rb2);


        //DO NOT REMOVE
        //panel.addStyleName(GAME_PANEL_STYLE_NAME);
//        final AsyncCallback callback = new AsyncCallback() {
//            public void onFailure(Throwable caught) {
//                panel.add(new HTML("Failed:" + caught.getMessage()));
//            }
//
//            public void onSuccess(Object result) {
//                Base.this.label.setText(result.toString());
//            }
//        };

//        Button button = new Button("Create Station entity", new ClickHandler() {
//            @Override
//            public void onClick(ClickEvent event) {
//                PFuelTank pFuelTank = new PFuelTank();
//                pFuelTank.pSize = new PSize(100, 200);
//                pFuelTank.pCoordinates = new PCoordinates(1, 2);
//                pFuelTank.setMaxCapacity(100);
//                pFuelTank.setCurrentCapacity(0);
//                PStation pStation = new PStation();
//                pStation.pSize = new PSize(3000, 4000);
//                pStation.getTanks().add(pFuelTank);
//                pFuelTank.setStationId(pStation);
//                RPCService rpc = new RPCService();
//                rpc.testRPC(pStation, callback);
//            }
//        });
        RootPanel.get("webName").add(new InlineLabel("Веб симулятор АЗС"));
        RootPanel.get("param1").add(new InlineLabel("Параметры моделирования"));
        RootPanel.get("black").setVisible(false);
        h2one.setStyleName("h2class");

        cashOfficeItem = new CashOfficeItem();
        petrolPumpItem = new PetrolPumpItem();
        grassItem = new GrassItem();
        startItem = new StartItem();
        exitItem = new ExitItem();
        iconPanel.add(new Label("Объекты АЗС:"));
        iconPanel.add(petrolPumpItem);
        iconPanel.add(cashOfficeItem);
        iconPanel.add(startItem);
        iconPanel.add(exitItem);
        iconPanel.add(grassItem);

        final ListBox sizeField = new ListBox();
        sizeField.addItem("8");
        sizeField.addItem("10");
        sizeField.addItem("12");
        sizeField.addItem("14");
        sizeField.setWidth("150");

        iconPanel.setSpacing(5);
        Button stepBackButton = new Button("Задание параметров");
        stepBackButton.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                //RootPanel.get("tableViewParam").setVisible(false);
                RootPanel.get("divStart").setVisible(true);
                RootPanel.get("divWork").setVisible(false);
            }
        });
        buttonsPanel.add(stepBackButton);
        buttonsPanel.add(runAppButton);
        buttonsPanel.add(waitButton);
        RootPanel.get("leftMiddle").add(iconPanel);
        RootPanel.get("leftMiddle").add(propertiesPanel);
        RootPanel.get("centerMiddle").add(gamePanel);
        RootPanel.get("rightMiddle").add(infoTabPanel);
        RootPanel.get("centerTop").add(modePanel);
        RootPanel.get("centerBottom").add(buttonsPanel);
        Button btnLoadModel = new Button("Задание конструктора");
        btnLoadModel.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                RootPanel.get("divWork").setVisible(true);
                RootPanel.get("divStart").setVisible(false);
                int index = sizeField.getSelectedIndex();
                widthL = Integer.parseInt(sizeField.getItemText(index));
                heightL = widthL;
                fuelTankPoint = new PCoordinates(0,heightL-2);
                cellTable = new CellTable(widthL, heightL);
                gamePanel.clear();
                gamePanel.add(cellTable);
                setMode(true);
            }
        });
        final ListBox distributionLaw = new ListBox();
        distributionLaw.addItem("", "100");
        distributionLaw.addItem("Равномерный", "0");
        distributionLaw.addItem("Нормальный", "1");
        distributionLaw.addItem("Показательный", "2");
        distributionLaw.setWidth("150");
        final TextBox textBox1 = new TextBox();
        textBox1.setWidth("40");
        final TextBox textBox2 = new TextBox();
        textBox2.setWidth("40");
        distributionLaw.addChangeHandler(new ChangeHandler() {
            @Override
            public void onChange(ChangeEvent event) {
                indexDistribution = Integer.parseInt(distributionLaw.getValue((distributionLaw.getSelectedIndex())));
                if (indexDistribution == 100) {
                    RootPanel.get("gameLawOption").clear();
                }
                if (indexDistribution == 0) {
                    RootPanel.get("gameLawOption").clear();
                    RootPanel.get("gameLawOption").add(new InlineLabel("A="));
                    RootPanel.get("gameLawOption").add(textBox1);
                    RootPanel.get("gameLawOption").add(new InlineLabel(" B="));
                    RootPanel.get("gameLawOption").add(textBox2);
                    k1 = Integer.parseInt(textBox1.getValue());
                    k2 = Integer.parseInt(textBox2.getValue());
                }
                ;
                if (indexDistribution == 1) {
                    RootPanel.get("gameLawOption").clear();
                    RootPanel.get("gameLawOption").add(new InlineLabel("Мат. ожидание="));
                    RootPanel.get("gameLawOption").add(textBox1);
                    RootPanel.get("gameLawOption").add(new InlineLabel(" Дисперсия="));
                    RootPanel.get("gameLawOption").add(textBox2);
                    k1 = Integer.parseInt(textBox1.getValue());
                    k2 = Integer.parseInt(textBox2.getValue());
                }
                ;
                if (indexDistribution == 2) {
                    RootPanel.get("gameLawOption").clear();
                    RootPanel.get("gameLawOption").add(new InlineLabel("Лямбда="));
                    RootPanel.get("gameLawOption").add(textBox1);
                    k1 = Integer.parseInt(textBox1.getValue());
                }
                ;
            }
        });

        RootPanel.get("sizeFieldLabel").add(new InlineLabel("Размерность поля"));
        RootPanel.get("sizeField").add(sizeField);
        RootPanel.get("gameLawLabel").add(new InlineLabel("Закон распределения"));
        RootPanel.get("gameLaw").add(distributionLaw);
        textBoxFuel = new TextBox();
        textBoxFuel.setValue("400.0");
        RootPanel.get("patrolSizeLabel").add(new InlineLabel("Минимально допустимый уровень топлива в цистерне"));
        RootPanel.get("patrolSize").add(textBoxFuel);
        textBoxCash = new TextBox();
        textBoxCash.setValue("100000");
        RootPanel.get("cashBoxLabel").add(new InlineLabel("Максимально допустимый размер кассы"));
        RootPanel.get("cashBox").add(textBoxCash);
        RootPanel.get("btnGoToWork").add(btnLoadModel);
        InlineLabel ref = new InlineLabel("Справка");
        ref.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                Window.Location.assign(GWT.getHostPageBaseURL() + "Reference.html");
            }
        });
        InlineLabel authors = new InlineLabel("Авторы");
        authors.addClickHandler(new ClickHandler() {
            @Override
            public void onClick(ClickEvent event) {
                Window.Location.assign(GWT.getHostPageBaseURL() + "Authors.html");
            }
        });
        RootPanel.get("ref").add(ref);
        RootPanel.get("authors").add(authors);
        dialogBoxContents.add(errorMessage);
        dialogBoxContents.add(dialogCloseButton);
        dialogbox.setWidget(dialogBoxContents);
    }


    public void init() {

        try {
            wave = new Wave(widthL, heightL);
            cellTable.createFieldElements(); // считывание шаблона и создание соответсвующих объектов(колонок, касс, въездов...)
            if (office == null)
                throw new RuntimeException("Объект кассы не создан");
            if (cellTable.getInPoint() == null)
                throw new RuntimeException("Въезд на АЗС не указан");
            if (cellTable.getOutPoint() == null)
                throw new RuntimeException("Выезд с АЗС не указан");
            office.addListener(this);
            pumps = cellTable.getPumps();

            if (pumps.isEmpty())
                throw new RuntimeException("Нужна хотя бы одна колонка на поле");
            for (PPetrolPump p : pumps) {
                if (!wave.isEmpty(p.getFillingPlace()))
                    throw new RuntimeException("Место под колонкой должно быть свободно");
                Label number = new Label(String.valueOf(p.getNumber()));
                Label fuelType = new Label(p.getFuelType());
                Label litreHasFilled = new Label("0");
                Label cost = new Label("0");
                p.initDisplay(litreHasFilled, cost);
                extPumpFlexTable.addRow(number, fuelType, litreHasFilled, cost);
            }

            for (int i = 0; i < heightL; i++) { //инициализация шоссе
                wave.modifyMap(widthL - 1, i, Wave.ROAD);
                wave.modifyMap(widthL - 2, i, Wave.ROAD_BORDER);
            }

            if (cellTable.getInPoint() != null) {
                inCoord = cellTable.getInPoint();
                wave.setInCoord(inCoord);
                wave.modifyMap(inCoord, Wave.EMPTY);
            }
            if (cellTable.getOutPoint() != null) {
                outCoord = cellTable.getOutPoint();
                wave.setOutCoord(outCoord);
                wave.modifyMap(outCoord, Wave.EMPTY);
            }
            for (int i = 0; i < widthL; i++)
                for (int j = 0; j < heightL; j++) {
                    DraggableContent content = cellTable.getCellContent(i, j);
                    if (content != null && !content.getName().equals("exit") && !content.getName().equals("start"))
                        wave.modifyMap(i, j, Wave.STATIC_OBJECTS);
                    else
                        wave.modifyMap(i, j, Wave.EMPTY);
                }
            isInitialized = true;
        } catch (RuntimeException e) {
            RootPanel.get("black").setVisible(true);
            errorMessage.setText(e.getMessage());
            dialogbox.center();
            dialogbox.show();
        }
    }

    public void lifeStep() { //основной цикл
        for (SimpleCar c : cars) {
            if (c.mustBeDeleted)
                continue;
            if (c instanceof Car) {
                Car car = (Car) c;
                if ((!car.isProcFinished() &&
                        redefineTargetPumpCount == 10 && c.getState() != State.Processing) || car.getFillingPump() == null)
                    setNearPump(car);
            }
            if (c instanceof IncasatorCar && c.getTarget() == null)
                c.setTarget(office.getNearCoordinates());
            if (c instanceof RefuellerCar && c.getTarget() == null)
                c.setTarget(getFuelTankPointFillingPlace());
            if (c.getState() == State.Standing)
                stand(c);
            if (c.getState() == State.Moving)
                paintCarMove(c);
            if (c.getState() == State.Processing)
                processing(c);
        }
    }

    public void paintCarMove(SimpleCar c) { //отображение движения машины. повторяется 10 циклов
        if (c.getDirection() == Direction.Right)
            gamePanel.setWidgetPosition(c, c.widgetLeftPos += repaintValue, c.widgetTopPos);
        if (c.getDirection() == Direction.Left)
            gamePanel.setWidgetPosition(c, c.widgetLeftPos -= repaintValue, c.widgetTopPos);
        if (c.getDirection() == Direction.Up)
            gamePanel.setWidgetPosition(c, c.widgetLeftPos, c.widgetTopPos -= repaintValue);
        if (c.getDirection() == Direction.Down)
            gamePanel.setWidgetPosition(c, c.widgetLeftPos, c.widgetTopPos += repaintValue);
        c.changeImage(); // перерисовка картинки машины в зависимости от направления
        c.movingCounter += 1;
        if (c.movingCounter == 10) {
            c.movingCounter = 0;
            c.setState(State.Standing);
        }
    }

    public boolean createNewCar() {
        PCoordinates coordinates = new PCoordinates(cellTable.getStartCoordinates().x, cellTable.getStartCoordinates().y);
        SimpleCar car;
        if (wave.isEmpty(coordinates)) {
            if (isCashOfficeFull && !isIncasatorCalled) {
                car = new IncasatorCar(office,coordinates, "A92");
                isCashOfficeFull = false;
                isIncasatorCalled = true;
            } else if (isFuelTankEmpty && !isRefuellerCalled) {
                car = new RefuellerCar(coordinates, finishedFuelType);
                isFuelTankEmpty = false;
                isRefuellerCalled = true;
            } else
                car = new Car(coordinates, "A92");
            if (car instanceof RefuellerCar)
                car.setPriorityTarget(cellTable.getRefuellerInOutPoint());
            else
                car.setPriorityTarget(cellTable.getInPoint());
            wave.modifyMap(coordinates, Wave.CARS);
            cars.add(car);
            gamePanel.add(car, car.widgetLeftPos, car.widgetTopPos);
            return true;
        }
        return false;
    }

    public void stand(SimpleCar c) { //цикл расчета дальнейшего действия и начало движения
        if (c.isReachTarget()) {
            if (c.isPriorityTarget()) {
                c.setPriorityTarget(null);
                return;
            }
            if ((c.getCoordinates().x == cellTable.getExitCoordinates().x) && (c.getCoordinates().y == cellTable.getExitCoordinates().y)) {
                c.mustBeDeleted = true;
                gamePanel.remove(c);
                wave.modifyMap(c.getCoordinates(), Wave.ROAD);
                if (c instanceof IncasatorCar) {
                    isIncasatorCalled = false;
                    isCashOfficeFull = false;
                    commonProfit+=((IncasatorCar)c).getGettingCash();
                    commonProfitLabel.setText(String.valueOf(commonProfit));
                }
                if (c instanceof RefuellerCar)
                    isRefuellerCalled = false;
            }
            if (!c.isProcFinished())
                c.setState(State.Processing);
            else {
                if (c instanceof RefuellerCar)
                    c.setPriorityTarget(cellTable.getRefuellerInOutPoint());
                else
                    c.setPriorityTarget(cellTable.getOutPoint());
                c.setTarget(cellTable.getExitCoordinates());
            }
        } else {
            try {
                if (c.getTarget() == null) //если все таки не найдена колонка, уезжаем нахер
                    c.setTarget(cellTable.getExitCoordinates());
                Move move = wave.FindWayAStar(c.getCoordinates(), c.getTarget(), c.getPrevStep(), c.cellState, c.getQueneNumber());
                if (move != null) {
                    c.setNextStep(move.coordinates);
                    wave.modifyMap(c.getCoordinates(), c.cellState);//текущая освобождается
                    c.cellState = wave.getValue(move.coordinates); //запоминание состояния
                    wave.modifyMap(move.coordinates, Wave.CARS); //след клетка занята
                    c.setDirection(move.direction);
                    c.doStep();
                    c.setState(State.Moving);
                }
            } catch (Exception e) {
                errorMessage.setText(e.getMessage());
                dialogbox.center();
                dialogbox.show();

            }
        }
    }

    /**
     * 1. Заправка обычной машины
     * 2. Заправка баков заправочной машиной
     * 3. Обработка кассы инкасацией
     */
    public void processing(SimpleCar c) {
        if (c instanceof Car) {
            Car car = (Car) c;
            PPetrolPump fillingPump = car.getFillingPump();
            if (!fillingPump.isEmpty()) {
                fillingPump.setBusy(true);
                car.increaseCurrentCapacity(fillingSpeed);
                fillingPump.descreaseFuel(fillingSpeed);
                if (c.isProcFinished()) {
                    car.finishFilling(cellTable.getOutPoint(), cellTable.getExitCoordinates());
                    double fuelDiff = car.getFuelDifference();
                    double price = office.increaseCash(fuelDiff, c.getFuelType());
                    fillingPump.refreshDisplay(fuelDiff, price);
                    //fillingPump.getConnectedFuelTank().refreshDisplay();
                    displayOfficeCash();
                }
            }
        }
        if (c instanceof IncasatorCar) {
            ((IncasatorCar)c).setGettingCash(office.incasatorEvent());
            if (c.isProcFinished()) {
                displayOfficeCash();
                c.finishFilling(cellTable.getOutPoint(),cellTable.getExitCoordinates());
                c.setState(State.Standing);
            }
        }
        if (c instanceof RefuellerCar) {
            refuellerEvent(finishedFuelType);
            if (c.isProcFinished()) {
                c.setState(State.Standing);
                c.finishFilling(cellTable.getRefuellerInOutPoint(),cellTable.getExitCoordinates());
            }
        }
    }

    public void setNearPump(Car c) { //выбор для машины ближайшей колонки с соответсвующим типом топлива //todo exception
        PPetrolPump resultPump = null;
        TreeMap<Integer, PPetrolPump> secondMap = new TreeMap<Integer, PPetrolPump>();
        TreeMap<Integer, PPetrolPump> minMap = new TreeMap<Integer, PPetrolPump>();
        for (PPetrolPump p : pumps) {
            int value = Wave.getSimpleMinWay(c.getCoordinates(), p.pCoordinates);
            if (minMap.get(value) == null)
                minMap.put(value, p);
            else
                secondMap.put(value, p);

        }
        Iterator<Map.Entry<Integer, PPetrolPump>> iterator = minMap.entrySet().iterator();
        while (resultPump == null && iterator.hasNext()) {
            Map.Entry<Integer, PPetrolPump> entry = iterator.next();
            PPetrolPump pump = entry.getValue();
            int minKey = entry.getKey();
            if (c.getFuelType().equals(pump.getFuelType())) {
                if (pumps.size() > 1) {
                    if (!pump.isBusy())
                        resultPump = pump;
                    else if (secondMap.get(minKey) != null)
                        resultPump = secondMap.get(minKey);
                } else
                    resultPump = pump;
            }
        }
        if (resultPump == null)
            resultPump = minMap.entrySet().iterator().next().getValue();
        if (resultPump == null)
            throw new RuntimeException("oyeee");
        c.setFillingPump(resultPump);
    }


    public void setMode(boolean value) {
        if (cellTable != null)
            cellTable.setEnable(value);
        cellTable.isDragMode = value;
        iconPanel.setVisible(value);
        propertiesPanel.setVisible(!value);
    }

    public void displayFuelDeal(double price, double fuelDifference) {
        displayOfficeCash();       //.substring(0,8)
        litreHasFilled.setText(String.valueOf(fuelDifference));   //5
        cost.setText(String.valueOf(price));           //7
        fuelA92Capacity.setText(String.valueOf(tank92.getCurrentCapacity()));  //6
    }

    public void displayOfficeCash() {
        currentMoneyInOfficeLabel.setText(String.valueOf(office.getCash()));
    }

    public static SimpleCar getCarByCoodinates(PCoordinates coordinates) {
        for (SimpleCar c : cars)
            if (c.getCoordinates().equals(coordinates))
                return c;
        return null;
    }

    public static PFuelTank getTank92() {
        return tank92;
    }

    public static PFuelTank getTank95() {
        return tank95;
    }

    public static PFuelTank getTankDiesel() {
        return tankDiesel;
    }

    public static PCashOffice getCashOffice() {
        return office;
    }

    public static PCoordinates getFuelTankPoint() {
        return fuelTankPoint;
    }

    public PCoordinates getFuelTankPointFillingPlace() {
        return new PCoordinates(fuelTankPoint.x + 1, fuelTankPoint.y);
    }


    public static void setCashOffice(PCashOffice office) {
        Base.office = office;
    }

    public void initTabsheets() {

        Label currentA92Label = new Label();
        Label currentA95Label = new Label();
        Label currentDieselLabel = new Label();

        ExtFlexTable mainExtFlexTable = new ExtFlexTable();
        mainExtFlexTable.addRow(new Label("Суммарная прибыль"), commonProfitLabel); //todo
        mainExtFlexTable.addRow(new Label("Текущий счет в кассе"), currentMoneyInOfficeLabel);

        ExtFlexTable fuelExtFlexTable = new ExtFlexTable();
        fuelExtFlexTable.addRow(new Label("Тип топлива"), new Label("Емкость"));
        fuelExtFlexTable.addRow(new Label("A92"), currentA92Label);
        fuelExtFlexTable.addRow(new Label("A95"), currentA95Label);
        fuelExtFlexTable.addRow(new Label("DIESEL"), currentDieselLabel);
        tank92.initDisplay(currentA92Label);
        tank95.initDisplay(currentA95Label);
        tankDiesel.initDisplay(currentDieselLabel);

        extPumpFlexTable = new ExtFlexTable();
        extPumpFlexTable.addRow(new Label("№"), new Label("Тип топлива"), new Label("Литров заправлено"), new Label("Стоимость"));

        infoTabPanel = new DecoratedTabPanel();
        infoTabPanel.add(mainExtFlexTable, "Основное");
        infoTabPanel.add(fuelExtFlexTable, "Баки");
        infoTabPanel.add(extPumpFlexTable, "Колонки");
        infoTabPanel.selectTab(0);
        infoTabPanel.setWidth("430");
        infoTabPanel.setVisible(false);
    }

    @Override
    public void fireRefuellerEvent(String fuelType) {
        finishedFuelType = fuelType;
        isFuelTankEmpty = true;

    }

    @Override
    public void fireIncasatorEvent() {
        isCashOfficeFull = true;
    }

    public void refuellerEvent(String fuelType) {
        if (fuelType.equals("A92"))
            tank92.fillUp(refuellerFillSpeed);
        if (fuelType.equals("A95"))
            tank95.fillUp(refuellerFillSpeed);
        if (fuelType.equals("DIESEL"))
            tankDiesel.fillUp(refuellerFillSpeed);
    }
}
